import React from 'react';
import { Button, Table, Form, Pagination } from 'antd';
import AddForm from './Install';
import './index.less';
import ShowMessage from './ShowMessage';
import Tips from '../../Tips/index';
import { connect } from 'react-redux';
import statuscode from '../../statuscode/index';
import Arrange from './arrange/index';
import Upgrade from './upgrade/index';
import Operation from './operation/index';
import Bread from '../../common/Bread/index';
import { installChaincodeSand, queryChainCodesSand, queryChainTemplateListSand, instantiateChainCodeReqSand, upgradeChainCodeReqSand, chaincodeOperatorSand } from '../../services/services';

const chainCodeStatus = {
  1000: '安装中',
  1010: '安装成功',
  1020: '安装失败',
  2010: '部署成功',
  2020: '部署失败',
  2000: '部署中',
  3010: '升级成功',
  3020: '升级失败',
  3000: '升级成功待部署',
};
class chainCode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: ['10', '20', '30', '40', '50', '60', '70', '80', '90'],
      visibleshowmessage: false,
      message: '',
      selectedRowKeys: [],
      selectStatus: true,
      limit: 10,
      pagenum: 1,
      RegisterKeyByUsername: '',
      timeout: false,
      templatedata: [],
      boxdata: '',
      showmessage: '',
      arrangevisible: false,
      upgradevisible: false,
      operationvisible: false,
      upgradeLoading: false,
      arrangeLoading: false
    };
  }
  componentWillMount() {
    this.ismounted = true;
    this.getData();
  }
  componentWillReceiveProps(nextprops) {
    if (this.props.changeNetwork !== nextprops.changeNetwork) {
      this.getData(nextprops.changeNetwork, 1);
      this.setState({ pagenum: 1 });
    }
  }
  componentWillUnmount() {
    this.ismounted = false;
  }
  columns = [{
    title: '名称',
    dataIndex: '名称',
    key: '名称',
    // width: 200
  }, {
    title: '版本',
    dataIndex: '版本',
    key: '版本',
    // width: 100
  }, {
    title: '类型',
    dataIndex: '类型',
    key: '类型',
  }, {
    title: '状态',
    dataIndex: '状态',
    key: '状态',
  }, {
    title: '安装时间',
    dataIndex: '安装时间',
    key: '安装时间',
  }, {
    title: '操作',
    key: '操作',
    width: 200,
    render: (text, record) => (
      <span className="controlchaincodebtn" >
        {/* <TemplateBtn data={text} disable={text['状态'] != '创建成功'} controlbox={this.controlbox} /> */}
        <span className={((text['状态'] == '安装成功') || (text['状态'] == '部署失败') || (text['状态'] == '升级成功待部署')) ? 'chaincodespan' : 'disablednone'} onClick={this.arrangeshow.bind(this, text)} >部署</span>
        <span className={(text['状态'] == '部署成功') ? 'chaincodespan' : 'disablednone'} onClick={this.operationshow.bind(this, text)} >操作</span>
        <span style={{ marginRight: '0px' }} className={(text['状态'] == '部署成功') ? 'chaincodespan' : 'disablednone'} onClick={this.upgradeshow.bind(this, text)} >升级</span>
      </span>
    ),
  }];
  tips = (str) => {
    this.setState({
      message: str
    });
    setTimeout(() => {
      this.setState({
        message: ''
      });
    }, 1000);
  }
  showModal = () => {
    this.VerifyAuth(this.props.changeOrgid);
  }
  arrangeshow = (text) => {
    if (!((text['状态'] == '安装成功') || (text['状态'] == '部署失败') || (text['状态'] == '升级成功待部署'))) return;
    this.setState({
      arrangevisible: true,
      arrangeitem: text
    });
  }
  upgradeshow = (text) => {
    if (text['状态'] != '部署成功') return;
    this.setState({
      upgradevisible: true,
      upgradeitem: text
    });
  }
  handleChancel = () => {
    this.setState({
      visible: false,
      templatedata: '',
      visibleclose: false,
    });
  }
  // 创建Chaincode
  handleCreate = (selectid, values, templateId, installPath) => {
    let data = {};
    if (selectid == 0) {
      // 自建模板
      data = {
        'RequestType': 'installChaincode',
        'ChannelId': 'mychannel',
        'FabricFlag': this.props.changeNetwork,
        'ChainCodeInfo': {
          'ChainCodeName': values.ChainCodeName,
          'ChainCodeVersion': values.Version,
        },
        OrgId: this.props.changeOrgid,
        TemplateId: 0,
        TemplatePath: installPath
      };
    } else if (selectid == 1) {
      // 使用模板库
      data = {
        'RequestType': 'installChaincode',
        'ChannelId': 'mychannel',
        'FabricFlag': this.props.changeNetwork,
        'ChainCodeInfo': {
          'ChainCodeName': values.ChainCodeName
        },
        OrgId: this.props.changeOrgid,
        TemplateId: this.state.templatedata[templateId].templateId
      };
    }
    this.InstallChaincode(data);
  }
  // 部署Chaincode
  arrangeCreate = (initdata) => {
    var init = 'init,' + initdata;
    let data = {
      channelId: 'mychannel',
      orgId: this.props.changeOrgid,
      'fabricFlag': this.props.changeNetwork,
      channelcodeargs: init,
      chancodeId: this.state.arrangeitem.chancodeId,
      templateId: this.state.arrangeitem.templateId
    };
    this.InstantiateChainCodeReq(data);
  }
  // 操作chaincode
  operationCreate = (operationdata) => {
    let data = {
      ChannelId: 'mychannel',
      'FabricFlag': this.props.changeNetwork,
      OperateChaincode: {
        Args: operationdata,
        Orgid: this.props.changeOrgid,
        ChainCodeName: this.state.operationdata['名称']
      },
      'ChainCodeName': this.state.operationdata['名称'],
      'Orgid': this.props.changeOrgid,
      'RequestType': 'ChaincodeOperatorReq'
    };
    this.ChaincodeOperator(data);
  }
  // 升级Chaincode
  upgradeCreate=(version, path) => {
    let data = {
      ChannelId: 'mychannel',
      'FabricFlag': this.props.changeNetwork,
      ChainCodeInfo: {
        ChainCodeVersion: version,
        ChainCodeName: this.state.upgradeitem['名称'],
        chancodeId: this.state.upgradeitem.chancodeId
      },
      'OrgId': this.props.changeOrgid,
      'RequestType': 'installChaincode',
      TemplateId: 0,
      TemplatePath: path
    };
    this.UpgradeChainCodeReq(data);
  }
  installedchaincode = () => {
    this.setState({
      installedchaincodevisible: true,
    });
  }
  installedchaincodeChancel = () => {
    this.setState({
      installedchaincodevisible: false,
    });
  }

  onShowSizeChange = (current, pageSize) => {
    this.setState({ limit: pageSize, pagenum: current }, () => {
      this.getData(this.props.changeNetwork);
    });
  }

  onChange = (pageNumber) => {
    this.setState({ pagenum: pageNumber }, () => {
      this.getData(this.props.changeNetwork);
    });
  }
  // 查询Chaincode列表
  getData = (Network = this.props.changeNetwork, pagenum = this.state.pagenum) => {
    if (!Network) {
      this.setState({
        data: [],
        totalnum: 0,
      });
      return;
    }
    var data = {
      'networkName': Network,
      'channelId': 'mychannel',
      limit: this.state.limit,
      page: pagenum,
      orgId: this.props.changeOrgid
    };
    this.QueryChainCodes(data);
  }

  arrangeChancel = () => {
    this.setState({
      arrangevisible: false,
    });
  }
  operationshow = (text) => {
    if (text['状态'] != '部署成功') return;
    this.setState({
      operationvisible: true,
      operationdata: text
    });
  }
  operationChancel = () => {
    this.setState({
      operationvisible: false
    });
  }
  upgradeChancel = () => {
    this.setState({
      upgradevisible: false,
      upgradeclose: false
    });
  }
  handleChancelshowmessage = () => {
    this.setState({ visibleshowmessage: false });
  }
  // 表格勾选
  onSelectChange = (selectedRowKeys) => {
    this.setState({
      selectedRowKeys,
      selectStatus: false
    });
  }
  // 安装Chaincode
  async InstallChaincode(data) {
    this.setState({
      timeout: true
    });
    const response = await installChaincodeSand(data);
    if (response) {
      var code = response.code;
      if (statuscode[code] == undefined) code = 500;
      var message = statuscode[code];
      if (code == 2026) message = '您不是管理员';
      if (code == 200) message = '安装成功';
      if (message) {
        this.tips(message);
      }
      this.setState({
        visibleclose: true,
        templatedata: '',
        timeout: false
      });
      this.getData(this.props.changeNetwork);
    } else {
      this.setState({
        timeout: false
      });
    }
  }
  // 查询Chaincode列表
  async QueryChainCodes(data) {
    const response = await queryChainCodesSand(data);
    if (response) {
      let data = [];
      var code = response.code;
      if (statuscode[code] == undefined) code = 500;
      var message = statuscode[code];
      this.tips(message);
      let responsedata = response.data.rows;
      responsedata && responsedata.forEach((e, i) => {
        data.push({
          '状态': chainCodeStatus[e.ChainCodeStatus],
          key: String(i),
          '名称': e.ChainCodeName,
          '版本': e.ChainCodeVersion,
          '类型': e.templateId == '0' ? '自建Chaincode' : '模板Chaincode',
          '安装时间': e.createTime,
          templateId: e.templateId,
          chancodeId: e.chancodeId
        });
      });
      this.setState({
        data: data,
        totalnum: response.data.total,
      });
    }
  }
  // 判断是否是组织管理员
  async VerifyAuth(data) {
    this.QueryChainTemplateList();
  }
  // 查询模板列表
  async QueryChainTemplateList(data) {
    const response = await queryChainTemplateListSand(data);
    if (response) {
      var code = response.code;
      if (statuscode[code] == undefined) code = 500;
      var message = statuscode[code];
      if (code == 200) {
        if ((response.data && response.data.length == 0) || !response.data) {
          message = '暂无模板';
          setTimeout(() => {
            this.setState({
              visible: false,
            });
          });
        } else {
          setTimeout(() => {
            this.setState({
              templatedata: response.data.rows,
              visible: true,
            });
          });
        }
      }
      if (message) {
        this.tips(message);
      }
    }
  }
  // 部署Chaincode
  async InstantiateChainCodeReq(data) {
    this.setState({
      message: '部署至区块链，时间较长，请保持等待',
      arrangeLoading: true
    });
    const response = await instantiateChainCodeReqSand(data);
    if (response) {
      this.setState({
        message: ''
      });
      var code = response.code;
      if (statuscode[code] == undefined) code = 500;
      var message = statuscode[code];
      if (code == 200) {
        this.tips('部署成功！');
        this.setState({
          arrangevisible: false,
          arrangeLoading: false
        });
        this.getData(this.props.changeNetwork);
        return;
      }
      if (message) {
        this.tips(message);
      }
      setTimeout(() => {
        this.setState({
          arrangevisible: false,
          arrangeLoading: false
        });
        this.getData(this.props.changeNetwork);
      }, 1000);
    } else {
      this.setState({
        message: '',
        arrangeLoading: false
      });
    }
  }
  // 操作Chaincode
  async ChaincodeOperator(data) {
    const response = await chaincodeOperatorSand(data);
    if (response) {
      var code = response.code;
      if (statuscode[code] == undefined) code = 500;
      var message = statuscode[code];
      if (code == 200) {
        let detaildata = JSON.parse(response.data);
        this.setState({
          operationvisible: false,
          visibleshowmessage: true,
          detaildata: detaildata
        });
      }
      if (message) {
        this.tips(message);
      }
    }
  }
  // 升级Chaincode
  async UpgradeChainCodeReq(data) {
    this.setState({
      upgradeLoading: true,
      message: '升级至区块链，时间较长，请请保持等待',
    });
    const response = await upgradeChainCodeReqSand(data);
    if (response) {
      this.setState({
        message: '',
      });
      var code = response.code;
      if (statuscode[code] == undefined) code = 500;
      var message = statuscode[code];
      if (code == 200) {
        this.tips('升级成功！');
        this.setState({
          upgradeclose: true,
          upgradeLoading: false
        });
        this.getData(this.props.changeNetwork);
        return;
      }
      if (message) {
        this.tips(message);
      }
      setTimeout(() => {
        this.setState({
          upgradeclose: true,
          upgradeLoading: false
        });
        this.getData(this.props.changeNetwork);
      }, 1000);
    } else {
      this.setState({
        message: '',
        upgradeLoading: false
      });
    }
  }
  render() {
    const { selectedRowKeys, selectStatus } = this.state;
    const disabled = selectStatus ? 'disabled' : '';
    return (
      <div>
        <Bread bread={['合约管理', ['Chaincode管理', 'chaincode']]} />
        <div className="index-buttons chaincodebuttons">
          <Button type="primary" onClick={this.showModal} disabled={this.props.changeOrgid ? false : true}>安装Chaincode</Button>
          {/* <Button type="Default" onClick={this.installedchaincode} disabled={this.props.changeOrgid ? false : true}>安装已有Chaincode</Button> */}
        </div>

        <Table
          columns={this.columns}
          dataSource={this.state.data}
          bordered
          pagination={false}
        />
        <div className="page_foot">
          <span className="data_num">共{this.state.totalnum}条</span>
          <Pagination pageSizeOptions={this.state.page} current={this.state.pagenum} className="page" showSizeChanger showQuickJumper onShowSizeChange={this.onShowSizeChange} defaultCurrent={1} total={this.state.totalnum} onChange={this.onChange} />
        </div>
        <AddForm
          visible={this.state.visible}
          onCancel={this.handleChancel}
          onCreate={this.handleCreate}
          timeout={this.state.timeout}
          templatedata={this.state.templatedata}
          visibleclose={this.state.visibleclose}
        />
        <ShowMessage
          visible={this.state.visibleshowmessage}
          showmessage={this.state.detaildata}
          onCancel={this.handleChancelshowmessage}
        />
        <Arrange
          visible={this.state.arrangevisible}
          onCancel={this.arrangeChancel}
          onCreate={this.arrangeCreate}
          arrangeLoading={this.state.arrangeLoading}
        />
        <Operation
          visible={this.state.operationvisible}
          onCancel={this.operationChancel}
          onCreate={this.operationCreate}
        />
        <Upgrade
          visible={this.state.upgradevisible}
          onCancel={this.upgradeChancel}
          onCreate={this.upgradeCreate}
          data={this.state.upgradeitem}
          upgradeLoading={this.state.upgradeLoading}
          upgradeclose={this.state.upgradeclose}
        />
        <Tips message={this.state.message} />
      </div>
    );
  }
}

const ChainCode = Form.create()(chainCode);

export default connect((state) => {
  return { ...state };
})(ChainCode);

